// package: rewords-server-2024
// filename: admin
// author: diogoxiang@gmail.com
// time: 2024/12/13 17:44
// desc: 微信小程序 用户管理模块 Ctrl

package admin

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"rewords-server-2024/internal/library/ecode"
	"rewords-server-2024/internal/model/input/form"
	"rewords-server-2024/utility/ufun"

	"rewords-server-2024/api/admin"
	"rewords-server-2024/internal/consts"
	"rewords-server-2024/internal/model/entity"
	"rewords-server-2024/internal/model/input/query_in"
	"rewords-server-2024/internal/service"

	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
)

var Wuser = new(cWuser)

type cWuser struct{}

// QueryList retrieves a list of users based on the provided conditions, order, and pagination parameters.
// It constructs a MongoDB query, executes it, and converts the results into a list of SysUser entities.
// Additionally, if the request specifies a need for the total count of matching documents, it fetches and includes this count in the response.
// Returns an error if any step fails, wrapping the original error with context.
func (c *cWuser) QueryList(ctx context.Context, req *admin.WuserListReq) (res *admin.WuserListRes, err error) {
	query, skip, limit, sort, _ := query_in.BuildMongoQueryWithPage(req.Conditions, req.OrderFields, &req.Page, nil)
	g.Log().Debug(ctx, "MongoDB query conditions:", query)
	g.Log().Debug(ctx, "Skip:", skip, "Limit:", limit)

	// 查询数据
	result, err := service.Mgx().Find(ctx, consts.CUser, query, nil, skip, limit, sort)
	if err != nil {
		return nil, gerror.Wrap(err, "获取数据失败")
	}

	var data []entity.SysUser
	if err = gconv.Struct(result, &data); err != nil {
		return nil, gerror.Wrap(err, "数据转换失败")
	}

	var total int64
	if req.Page.QueryCount {
		total, err = service.Mgx().CountDocuments(ctx, consts.CUser, query)
		if err != nil {
			return nil, gerror.Wrap(err, "获取总数失败")
		}
	}

	return &admin.WuserListRes{
		List: ufun.If(len(data) > 0, data, []entity.SysUser{}),
		PageResult: query_in.PageResult{
			Total: total,
		},
	}, nil
}

func (c *cWuser) Add(ctx context.Context, req *admin.WuserAddReq) (res *admin.WuserAddRes, err error) {

	return
}

func (c *cWuser) Update(ctx context.Context, req *admin.WuserUpdateReq) (res *admin.WuserUpdateRes, err error) {

	updateDoc := form.NewBuilder().
		SetIfNotEmpty("nickname", req.Nickname).
		SetIfNotEmpty("phone", req.Phone).
		SetIfNotEmpty("unionid", req.UnionId).
		SetIfNotEmpty("openid", req.Openid).
		Set("avatar", req.Avatar).
		SetIfNotZero("level", req.Level).
		Set("points", req.Points).
		SetIfNotZero("role", req.Role).
		SetIfNotZero("status", req.Status).
		Build()

	result, err := service.Mgx().UpdateOne(
		ctx,
		consts.CUser,
		bson.M{"uid": req.Uid},
		bson.M{"$set": updateDoc})

	if err != nil {
		return nil, gerror.NewCode(ecode.InvalidParams)
	}

	if result.MatchedCount == 0 {
		return nil, gerror.NewCode(ecode.DataNotFound)
	}

	return &admin.WuserUpdateRes{
		Uid: req.Uid,
	}, nil

}
